package com.mininglamp.main;

import com.mininglamp.mode.Input;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.StatelessKieSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhouhuiyu on 17/9/13.
 */
public class TestKieBuilderMain {

    private static Logger logger = LoggerFactory.getLogger(TestKieBuilderMain.class);

    public static void main(String[] args){


        logger.info("TestKieBuilderMain is Starting....");

        StringBuilder drl = new StringBuilder();

        String rule1 =
        "package my.name.is.xiewendong;" + " " +
        "import com.mininglamp.mode.Input;" + " " +
        "rule \"rule.3\"" + " " +
        "no-loop true" + " " +
        "enabled true" + " " +
        "salience 30" + " " +
        "when" + " " +
        "fact:Input( ( sex== \"男\" ) )" + " " +
        "then" + " " +
        "System.out.println(\"rule.3 大帅哥一枚！！！！\");" + " " +
        "end" + " " +

        //String rule2 =
        "rule \"rule.4\"" + " " +
        "no-loop true" + " " +
        "enabled true" + " " +
        "salience 30" + " " +
        "when" + " " +
        "fact:Input( ( sex== \"女\" ) )" + " " +
        "then" + " " +
        "System.out.println(\"rule.4 美女一枚！！！！\");" + " " +
        "end" ;

        drl.append(rule1);
//        drl.append(rule2);

        String drlFile = "src/main/resources/simple.drl";

        KieServices kieService = KieServices.Factory.get();

        KieFileSystem kieFileSystem = kieService.newKieFileSystem();

        kieFileSystem.write(drlFile, drl.toString());

        KieBuilder kieBuilder = kieService.newKieBuilder(kieFileSystem);

        logger.info("build all start...");

        kieBuilder.buildAll();

        Results results = kieBuilder.getResults();

        if (results.hasMessages(Message.Level.ERROR))
        {
//            logger.error(results.getMessages().toString());
            System.out.println(results.getMessages());
            throw new IllegalStateException("### errors ####");
        }

        logger.info("build all end...");

        KieContainer kieContainer = kieService.newKieContainer(kieBuilder.getKieModule().getReleaseId());

        StatelessKieSession kieSession = kieContainer.newStatelessKieSession();

        Input input = new Input("刘磊", "男", "18", "湖南", 1.69D, 1500);

        kieSession.execute(input);

    }
}
